package com.game.config.netty;

import com.game.config.netty.server.MessageService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class MessageServiceImpl implements MessageService {
    private final Map<String, ChannelHandlerContext> playerChannels = new ConcurrentHashMap<>();

    @Override
    public void sendMessage(String playerId, String message) {
        ChannelHandlerContext ctx = playerChannels.get(playerId);
        if (ctx != null && ctx.channel().isActive()) {
            // 发送消息
            ctx.writeAndFlush(message);
        }
    }

    @Override
    public void subscribeToMessages(String playerId, ChannelHandlerContext ctx) {
        playerChannels.put(playerId, ctx);
    }

    @Override
    public void unsubscribeFromMessages(String playerId) {
        log.info("玩家频道: {}", playerChannels);
        playerChannels.remove(playerId);
    }
}
